﻿using System;


namespace BasicallyNot.CodeTransformers.Searchers
{

	internal class MustComeFirst : IVisualSearcher
	{

		void IVisualSearcher.Match( VisualSearcherEventArg arg, ref VisualSearchResult result )
		{
			result.IsMatch = false;

			int start = arg.LineText.IndexOf( arg.Keyword );
			if ( start < 0 )
				return;

			if ( start > 0 ) {
				char justBefore = arg.LineText[ start - 1 ];
				if ( char.IsLetterOrDigit( justBefore ) )
					return;
			}

			int justAfterIndex = start + arg.Keyword.Length;
			if ( justAfterIndex < arg.LineText.Length ) {
				char justAfter = arg.LineText[ justAfterIndex ];
				if ( char.IsLetterOrDigit( justAfter ) )
					return;
			}

			// make sure there is only whitespace before the keyword, and that we're not inside a comment
			for ( int i = 0; i < start; ++i ) {
				char c = arg.LineText[ i ];
				if ( !char.IsWhiteSpace( c ) )
					return;

				if ( c == '\'' )
					return;
			}

			result.MatchIndex = start;
			result.IsMatch = true;
		}

	}

}
